package Thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABCUsingLock {


    private final  int times; // 控制打印次数
    private volatile  int state;   // 当前状态值：保证三个线程之间交替打印
    private Lock lock = new ReentrantLock();

    public PrintABCUsingLock(int times) {
        this.times = times;
    }

    /**
     *  给3取模
     *  A: 0  3  6   9           A为膜为0情况
     *  B: 2  5  8   10          B为膜为1 情况
     *  C: 1  4  7   11          C为膜为2情况
     */
    private void printLetter(int targetNum) {
        for (int i = 0; i < times; ) {//相当于While循环
            lock.lock();
            if (state % 3 == targetNum) {
                state++;
                i++;//聪明的地方
                System.out.print(Thread.currentThread().getName());
                if(state%3==0){
                    System.out.print(" ");
                }
            }
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        PrintABCUsingLock loopThread = new PrintABCUsingLock(10);

        new Thread(() -> loopThread.printLetter(2), "C").start();
        new Thread(() -> loopThread.printLetter(1), "B").start();
        new Thread(() -> loopThread.printLetter(0), "A").start();

    }
}


